package com.xdh.zzqh.store

import com.xdh.zzqh.R
import com.xdh.zzqh.utils.runWithDb
import com.xdh.zzqh.utils.stringById

class User(
    val name: String
) {

    companion object {
        private const val TB_NAME = "tb_user"
        const val CREATE_SQL = "CREATE TABLE IF NOT EXISTS $TB_NAME (" +
                "id INTEGER PRIMARY KEY AUTOINCREMENT, " +
                "name TEXT NOT NULL UNIQUE" +
                ")"

        suspend fun delete(name: String) = runWithDb {
            SqliteConn.conn.execSQL("DELETE FROM $TB_NAME WHERE name = ?", arrayOf(name))
        }

        suspend fun queryAll() = runWithDb {
            val list = ArrayList<String>()
            val cursor = SqliteConn.conn.rawQuery("SELECT name FROM $TB_NAME", arrayOf())
            cursor.use {
                while (cursor.moveToNext()) {
                    val name = cursor.getString(0)
                    list.add(name)
                }
            }
            list
        }
    }

    suspend fun saveOnNotExists() {
        val cursor = SqliteConn.conn.rawQuery("SELECT name FROM $TB_NAME WHERE name = ?", arrayOf(name))
        val ret = cursor.use {
            cursor.moveToNext()
        }
        if (ret) {
            return
        }
        save()
    }

    suspend fun save() = runWithDb {
        val cursor = SqliteConn.conn.rawQuery("SELECT name FROM $TB_NAME WHERE name = ?", arrayOf(name))
        val ret = cursor.use {
            cursor.moveToNext()
        }
        if (ret) {
            throw IllegalStateException(stringById(R.string.ke_hu_ming_cheng_zhong_fu_le))
        }

        SqliteConn.conn.execSQL("INSERT INTO $TB_NAME (name) VALUES (?)", arrayOf(name))
    }
}